package com.youhong.teethcare;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.youhong.teethcare.javabeans.BrushingRecord;
import com.youhong.teethcare.utils.DBHelper;
import com.youhong.teethcare.utils.Util;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Column;
import lecho.lib.hellocharts.model.ColumnChartData;
import lecho.lib.hellocharts.model.SubcolumnValue;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.ColumnChartView;

public class DurationAnalysisActivity extends BaseActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_analysis);
        initStatusBar(Color.WHITE,true);

        getViews();
    }

    ImageView iv_back;
    TextView tv_week, tv_month, tv_year;
    TextView tv_prompt;
    ColumnChartView ccv;
    TextView tv_title;

    private void getViews() {

        tv_title = findViewById(R.id.analysis_tv_title);
        tv_title.setText(R.string.strings13);

        iv_back = findViewById(R.id.analysis_iv_back);
        iv_back.setOnClickListener(this);

        tv_week = findViewById(R.id.analysis_btn_week);
        tv_week.setOnClickListener(this);

        tv_month = findViewById(R.id.analysis_btn_month);
        tv_month.setOnClickListener(this);

        tv_year = findViewById(R.id.analysis_btn_year);
        tv_year.setOnClickListener(this);

        tv_prompt = findViewById(R.id.analysis_tv_prompt);

        ccv = findViewById(R.id.analysis_ccv);
        ccv.setInteractive(true);

        //是否允许点击柱状图数据。
        ccv.setValueTouchEnabled(false);
        tv_week.setSelected(true);
        int return_averageDuration = weekData();

        setPromptText(return_averageDuration);

        // ccv.setColumnChartData(weekData());
    }

    private void setPromptText(int val) {

        if (val < 120) {

            String average_str = (val / 60) + "' " + Util.concateZero(val % 60) + "''";
            tv_prompt.setText(String.format(getResources().getString(R.string.analysis_duration1)
                    , average_str));
        } else {

            String average_str = (val / 60) + "' " + Util.concateZero(val % 60) + "''";
            tv_prompt.setText(String.format(getResources().getString(R.string.analysis_duration2)
                    , average_str, "85%"));
        }
    }

    ColumnChartData data;



    private int weekData() {
        Calendar c = Calendar.getInstance();

        List<BrushingRecord> return_records =
                DBHelper.getDbHelper(getApplicationContext())
                        .queryBrushRecordByWeek(c.get(Calendar.YEAR)
                                , c.get(Calendar.WEEK_OF_YEAR) -1, 1);


        int dayDiff = c.get(Calendar.DAY_OF_WEEK) - c.getFirstDayOfWeek();
        //调整至本周的第一天
        c.add(Calendar.DAY_OF_YEAR, -dayDiff);

        List<Integer> average_duration = new ArrayList<>();

        int return_value = 0;

        for (BrushingRecord record : return_records) {
            return_value += record.getTotalTime();
        }

        if (return_records.size() != 0) {

            return_value = return_value / return_records.size();

        }

        //获取7天的平均刷牙时间，如果某天没有数据，也会占有一个空间，
        //值为0
        for (int i = 0; i < 7; i++) {

            List<BrushingRecord> records = DBHelper.getDbHelper(getApplicationContext()).queryBrushRecordByDay(c,1);
            c.add(Calendar.DAY_OF_YEAR, 1);

            if (records.size() == 0) {
                average_duration.add(0);
            } else {
                int count_duration = 0;
                for (BrushingRecord record : records) {

                    count_duration += record.getTotalTime();
                }
                average_duration.add(count_duration / records.size());

            }
        }

        ArrayList<Column> list = new ArrayList<>();
        //空出第一列和最后一列。 为了界面效果。
        average_duration.add(0, 0);
        average_duration.add(average_duration.size(), 0);

        //Adding Columns
        for (int i = 0; i < average_duration.size(); i++) {

            List<SubcolumnValue> subcolumns = new ArrayList<>();

            //等于0的不添加
            if (average_duration.get(i) != 0) {

                String label = "   " + Util.concateZero(average_duration.get(i) / 60)
                        + ":"
                        + Util.concateZero(average_duration.get(i) % 60);

                SubcolumnValue sub_col = new SubcolumnValue(
                        average_duration.get(i), columnColor
                );

                sub_col.setLabel(label);
                subcolumns.add(sub_col);

                Column column = new Column(subcolumns);
                column.setHasLabels(true);
                list.add(column);

            } else {
                //添加为0的Column
                SubcolumnValue sub_col = new SubcolumnValue(
                        0, Color.TRANSPARENT
                );

                subcolumns.add(sub_col);
                Column column = new Column(subcolumns);
                column.setHasLabels(false);
                list.add(column);
            }

        }

        data = new ColumnChartData(list);

        //设置Label背景
        data.setValueLabelBackgroundEnabled(false);
        //设置Label文字颜色
        data.setValueLabelsTextColor(Color.WHITE);

        //设置X轴显示.
        Axis axisX = new Axis();
        axisX.setTextColor(colorAxiesText);

        List<AxisValue> axisXValue = new ArrayList<>();
        axisXValue.add(new AxisValue(1).setLabel(getResources().getString(R.string.week_str1)));
        axisXValue.add(new AxisValue(2).setLabel(getResources().getString(R.string.week_str2)));
        axisXValue.add(new AxisValue(3).setLabel(getResources().getString(R.string.week_str3)));
        axisXValue.add(new AxisValue(4).setLabel(getResources().getString(R.string.week_str4)));
        axisXValue.add(new AxisValue(5).setLabel(getResources().getString(R.string.week_str5)));
        axisXValue.add(new AxisValue(6).setLabel(getResources().getString(R.string.week_str6)));
        axisXValue.add(new AxisValue(7).setLabel(getResources().getString(R.string.week_str7)));

        axisX.setValues(axisXValue);

        //设置Y轴显示.
        Axis axisY = new Axis().setHasLines(true).setHasTiltedLabels(false)
                .setLineColor(colorAxiesLine);

        List<AxisValue> axisYValue = new ArrayList<>();

        axisYValue.add(new AxisValue(120));
        axisYValue.add(new AxisValue(240));
        // axisYValue.add(new AxisValue(300));
        axisY.setValues(axisYValue);
        //不显示坐标轴上的刻度
        axisY.setHasAxisLabel(false);
        //不显示坐标轴的BaseLine.
        axisY.setHasSeparationLine(false);

        data.setAxisXBottom(axisX);
        data.setAxisYLeft(axisY);
        data.setFillRatio(0.1f);
        data.setValueLabelTextSize(10);
        ccv.setColumnChartData(data);

        //只允许纵向缩放
        ccv.setZoomType(ZoomType.HORIZONTAL);

        Viewport v = new Viewport(ccv.getMaximumViewport());
        v.left = 0;
        v.right = 7;
        ccv.setMaximumViewport(new Viewport(0, 330, 8, 0));
        ccv.setCurrentViewport(ccv.getMaximumViewport());

        return return_value;
    }

    int columnColor=Color.parseColor("#28A2FF");
    int colorAxiesLine=Color.parseColor("#CCCCCC");
    int colorAxiesText=Color.parseColor("#66000000");
    private int monthData() {

        Calendar c = Calendar.getInstance();
        List<BrushingRecord> records = DBHelper.getDbHelper(getApplicationContext())
                .queryBrushRecordGroupByMonth(c.get(Calendar.MONTH), c.get(Calendar.YEAR), 1);

        List<BrushingRecord> return_reocrds = DBHelper.getDbHelper(getApplicationContext())
                .queryBrushRecordByMonth(c.get(Calendar.MONTH), c.get(Calendar.YEAR), 1);

        int return_val = 0;

        //计算刷牙时长平均值
        for (BrushingRecord record : return_reocrds) {

            return_val += record.getTotalTime();
        }

        if (return_reocrds.size() != 0) {
            return_val = return_val / return_reocrds.size();
        }
        //初始化为每个月的第一天
        c.set(Calendar.DAY_OF_MONTH, 1);

        ArrayList<Column> list = new ArrayList<>();


        //Adding Columns

        //匹配日期，因为如果当日没有数据的情况下，在Records List之中是不存在记录的。
        for (int i = 0; i < c.getActualMaximum(Calendar.DATE) + 2; i++) {

            int averageVal = 0;
            for (BrushingRecord record : records) {

                int val = record.getStartTime().get(Calendar.DAY_OF_MONTH);

                if (record.getStartTime().get(Calendar.DAY_OF_MONTH) == c.get(Calendar.DAY_OF_MONTH)) {

                    averageVal = record.getTotalTime();
                    break;
                }
            }

            List<SubcolumnValue> subcolumns = new ArrayList<>();


            //空出第一列和最后一列。 为了界面效果。
            if (i == 0 || i == c.getActualMaximum(Calendar.DATE) + 1) {
                averageVal = 0;

            } else {
                c.add(Calendar.DAY_OF_MONTH, 1);
            }

            //添加有效的数据
            if (averageVal != 0) {

                String label = "   " + Util.concateZero(averageVal / 60)
                        + ":"
                        + Util.concateZero(averageVal % 60);

                SubcolumnValue sub_col = new SubcolumnValue(
                        averageVal,columnColor
                );

                sub_col.setLabel(label);
                subcolumns.add(sub_col);

                Column column = new Column(subcolumns);
                column.setHasLabels(true);
                list.add(column);

            } else {
                //添加为0的Column
                SubcolumnValue sub_col = new SubcolumnValue(
                        0, Color.TRANSPARENT
                );

                subcolumns.add(sub_col);
                Column column = new Column(subcolumns);
                column.setHasLabels(false);
                list.add(column);
            }

        }

        data = new ColumnChartData(list);

        //设置Label背景
        data.setValueLabelBackgroundEnabled(false);
        //设置Label文字颜色
        data.setValueLabelsTextColor(Color.WHITE);

        //设置X轴显示.
        Axis axisX = new Axis();
        axisX.setTextColor(colorAxiesText);

        List<AxisValue> axisXValue = new ArrayList<>();

        Calendar c1 = Calendar.getInstance();

        //循环把本月日期的坐标轴数据。
        for (int i = 1; i <= c1.getActualMaximum(Calendar.DAY_OF_MONTH); i++) {

            axisXValue.add(new AxisValue(i).setLabel(i + ""));
        }

        axisX.setValues(axisXValue);

        //设置Y轴显示.
        Axis axisY = new Axis().setHasLines(true).setHasTiltedLabels(false)
                .setLineColor(colorAxiesLine);

        List<AxisValue> axisYValue = new ArrayList<>();

        axisYValue.add(new AxisValue(120));
        axisYValue.add(new AxisValue(240));
        //axisYValue.add(new AxisValue(300));
        axisY.setValues(axisYValue);
        //不显示坐标轴上的刻度
        axisY.setHasAxisLabel(false);
        //不显示坐标轴的BaseLine.
        axisY.setHasSeparationLine(false);

        data.setAxisXBottom(axisX);
        data.setAxisYLeft(axisY);
        data.setFillRatio(0.1f);
        data.setValueLabelTextSize(10);

        ccv.setColumnChartData(data);

        //只允许纵向缩放
        ccv.setZoomType(ZoomType.HORIZONTAL);
        //允许滚动
        ccv.setScrollEnabled(true);
        ccv.setMaximumViewport(new Viewport(0, 330, 33, 0));

        Viewport v = new Viewport(ccv.getMaximumViewport());
        if (return_val == 0) {
            v.left = 0;
            v.right = 33;

        } else {
            int dayOfMonth = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);

            if (dayOfMonth > 4) {
                dayOfMonth -= 4;
                v.left = dayOfMonth;
                v.right = dayOfMonth + 8;

            } else {

                v.left = 0;
                v.right = 8;
            }

        }
        ccv.setCurrentViewport(v);
        return return_val;
    }

    private int yearData() {

        Calendar c = Calendar.getInstance();
        List<BrushingRecord> records = DBHelper.getDbHelper(getApplicationContext())
                .queryBrushRecordGroupByYear(c.get(Calendar.YEAR), 1);

        List<BrushingRecord> record_return = DBHelper.getDbHelper(getApplicationContext())
                .queryBrushRecordByYear(c.get(Calendar.YEAR), 1);

        int return_val = 0;

        //计算刷牙时长平均值
        for (BrushingRecord record : record_return) {

            return_val += record.getTotalTime();
        }

        if (record_return.size() != 0) {
            return_val = return_val / record_return.size();
        }

        ArrayList<Column> list = new ArrayList<>();
        //空出第一列和最后一列。 为了界面效果。

        //Adding Columns

        //匹配日期，因为如果当日没有数据的情况下，在Records List之中是不存在记录的。

        c.set(Calendar.MONTH, 0);
        for (int i = 0; i < c.getActualMaximum(Calendar.MONTH) + 2; i++) {

            int averageVal = 0;
            for (BrushingRecord record : records) {

                if (record.getStartTime().get(Calendar.MONTH) == c.get(Calendar.MONTH)) {

                    averageVal = record.getTotalTime();
                    break;
                }
            }

            List<SubcolumnValue> subcolumns = new ArrayList<>();

            if (i == 0 || i == c.getActualMaximum(Calendar.DATE) + 1) {
                averageVal = 0;

            } else {
                c.add(Calendar.MONTH, 1);
            }

            //等于0的不添加
            if (averageVal != 0) {

                String label = "   " + Util.concateZero(averageVal / 60)
                        + ":"
                        + Util.concateZero(averageVal % 60);

                SubcolumnValue sub_col = new SubcolumnValue(
                        averageVal, columnColor
                );

                sub_col.setLabel(label);
                subcolumns.add(sub_col);

                Column column = new Column(subcolumns);
                column.setHasLabels(true);
                list.add(column);

            } else {
                //添加为0的Column
                SubcolumnValue sub_col = new SubcolumnValue(
                        0, Color.TRANSPARENT
                );

                subcolumns.add(sub_col);
                Column column = new Column(subcolumns);
                column.setHasLabels(false);
                list.add(column);
            }

        }

        data = new ColumnChartData(list);

        //设置Label背景
        data.setValueLabelBackgroundEnabled(false);
        //设置Label文字颜色
        data.setValueLabelsTextColor(Color.WHITE);

        //设置X轴显示.
        Axis axisX = new Axis();
        axisX.setTextColor(colorAxiesText);

        List<AxisValue> axisXValue = new ArrayList<>();

        Calendar c1 = Calendar.getInstance();

        //循环加载所有月份的坐标轴数据。
        for (int i = 1; i <= c1.getActualMaximum(Calendar.MONTH) + 1; i++) {

            axisXValue.add(new AxisValue(i).setLabel(DatePickerActivity.returnMonth(getApplicationContext(),i - 1)));

        }
        axisX.setMaxLabelChars(6);
        axisX.setTextSize(10);
        axisX.setValues(axisXValue);

        //设置Y轴显示.
        Axis axisY = new Axis().setHasLines(true).setHasTiltedLabels(false)
                .setLineColor(colorAxiesLine);

        List<AxisValue> axisYValue = new ArrayList<>();

        axisYValue.add(new AxisValue(120));
        axisYValue.add(new AxisValue(240));
        //axisYValue.add(new AxisValue(300));
        axisY.setValues(axisYValue);
        //不显示坐标轴上的刻度
        axisY.setHasAxisLabel(false);
        //不显示坐标轴的BaseLine.
        axisY.setHasSeparationLine(false);

        data.setAxisXBottom(axisX);
        data.setAxisYLeft(axisY);
        data.setFillRatio(0.25f);
        data.setValueLabelTextSize(10);

        ccv.setColumnChartData(data);

        //只允许纵向缩放
        ccv.setZoomType(ZoomType.HORIZONTAL);
        //允许滚动
        ccv.setScrollEnabled(true);
        ccv.setMaximumViewport(new Viewport(0, 330, 13, 0));

        Viewport v = new Viewport(ccv.getMaximumViewport());
        v.left = 0;
        v.right = 13;
        ccv.setCurrentViewport(v);
        return return_val;
    }


    @Override
    public void onClick(View v) {

        if (v == tv_week) {


            tv_week.setSelected(true);
            tv_month.setSelected(false);
            tv_year.setSelected(false);
            int return_val = weekData();
            setPromptText(return_val);


        } else if (v == tv_month) {

            tv_week.setSelected(false);
            tv_month.setSelected(true);
            tv_year.setSelected(false);
            int return_val = monthData();
            setPromptText(return_val);

        } else if (v == tv_year) {

            tv_week.setSelected(false);
            tv_month.setSelected(false);
            tv_year.setSelected(true);
            int return_val = yearData();
            setPromptText(return_val);

        } else if (v == iv_back) {

            this.finish();

        }

    }
}
